<template>
  <el-cascader
    v-model="selectedValue"
    :placeholder="placeholder"
    :size="size"
    :props="props"
    :options="selectOptions"
    :clearable="clearable"
  >
  </el-cascader>
</template>

<script>
import TreeUtil from '@/framework/infra/util/TreeUtil'

export default {
  name: 'Cascader',
  data() {
    return {
      selectedValue: [],
      selectOptions: []
    }
  },
  watch: {
    selectedValue() {
      this.$emit('input', this.selectedValue)
    },
    value() {
      this.selectedValue = this.getValue()
    },
    async options() {
      this.selectOptions = await this.getOptions()
    }
  },
  async created() {
    this.selectOptions = await this.getOptions()
    this.selectedValue = this.getValue()
  },
  methods: {
    getValue() {
      if (!this.value) {
        return []
      }
      if (Array.isArray(this.value)) {
        return this.value
      }
      if (typeof this.value === 'number') {
        return TreeUtil.getPath(this.selectOptions, this.value)
      }
      return this.value.split(',').map(el => parseInt(el))
    },
    async getOptions() {
      if (Array.isArray(this.options)) {
        return this.options
      }
      if (this.options instanceof Promise) {
        return await this.options
      }
      return this.options.getOptions()
    }
  },
  props: {
    value: {
      type: [Array, Number, String],
      default: null
    },
    props: {
      type: Object,
      default() {
        return {}
      }
    },
    options: {
      type: [Array, Object, Function, Promise],
      default() {
        return []
      }
    },
    valuePropName: {
      type: String,
      default: 'value'
    },
    size: {
      type: String,
      default: 'mini'
    },
    labelPropName: {
      type: String,
      default: 'label'
    },
    placeholder: {
      type: String,
      default: ''
    },
    clearable: {
      type: Boolean,
      default: false
    }
  }
}
</script>
